<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理的内容 -->
      <div class="role-operate">
        <el-button type="primary" size="mini" @click="showDialog = true"> 添加角色</el-button>
      </div>
      <!-- 放置表格 -->
      <el-table :data="fromData">
        <!-- 放置列 -->
        <el-table-column label="角色" width="200" align="center" prop="name">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini"> </el-input>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" width="200" align="center" prop="state">
          <!-- 自定义结构 -->
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" size="mini" v-model="row.editRow.state" :active-value="1" :inactive-value="0">
            </el-switch>
            <span v-else> {{ row.state === 1 ? '已启用' : '已禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="description">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" type="textarea" size="mini" :rows="4" v-model="row.editRow.description">
            </el-input>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <!-- 放置操作按钮 -->
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="btnEditOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button @click="btnEdit(row)" type="text" size="mini">编辑</el-button>
              <el-popconfirm confirm-button-text='好的' cancel-button-text='不用了' icon="el-icon-info" icon-color="red"
                title="是否删除吗？" @onConfirm="confirmDel(row.id)">
                <!-- 需要onConfirm才能触发 -->
                <el-button type="text" size="mini" slot="reference" style="padding: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页 -->
      <el-row type='flex' justify="end" style="height: 60px;" align="middle">
        <!-- 放置分页组件 -->
        <el-pagination layout="prev, pager, next" :page-size="pageParmas.pagesize" :total="pageParmas.total"
          :current-page="pageParmas.page" @current-change="handleCurrentChange"></el-pagination>
      </el-row>
    </div>
    <div>
      <!-- 放置弹层组件 -->
      <el-dialog title="新增角色" :visible.sync="showDialog" @close="btnCancel">
        <!-- 放置表单组件 -->
        <el-form label-width="120px" :model="roleFrom" :rules="rules" ref="roleFrom">
          <el-form-item label="角色名称" prop="name">
            <el-input size="mini" style="width: 300px;" v-model="roleFrom.name"></el-input>
          </el-form-item>
          <!-- 不校验就不需要prop绑定 -->
          <!-- 重置表单需要用到prop属性 -->
          <el-form-item label="启用" prop="state">
            <el-switch size="mini" v-model="roleFrom.state" :active-value="1" :inactive-value="0">
            </el-switch>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input type="textarea" style="width: 300px;" :rows="4" size="mini"
              v-model="roleFrom.description"></el-input>
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" @click="btnOk">确定</el-button>
                <el-button @click="btnCancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!-- 放置权限弹层 -->
    <el-dialog :visible.sync="showPromissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree 
      node-key="id"
      check-strictly
      :data="permissionData"
      :props="{
        label: 'name'
      }"
      :show-checkbox="true"
      :default-expand-all="true"
      :default-checked-keys="permIds"
      ref="permTree">

      </el-tree>
      <el-row type="flex" justify="center" slot="footer">
        <el-col  :span="6">
          <el-button type="primary" @click="btnRoleOk">确定</el-button>
          <el-button @click="showPromissionDialog=false">取消</el-button>
        </el-col>
      </el-row>  

    </el-dialog>
  </div>

</template>
<script>
import { 
  getRoleList,
   addRole, 
   updateRole, 
   deleteRole ,
   getRoleDetail,
   assignPerm
  } from '@/api/role'
import {getPermissionList} from '@/api/permission'
import { transListToTreeData } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      fromData: [],
      pageParmas: {
        page: 1, // 当前页码
        pagesize: 5, // 每页显示条数
        total: 0
      },
      showDialog: false,
      roleFrom: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },

        ],
      },
      showPromissionDialog: false,
      permissionData:[],
      currentRoleId: '',
      permIds:[]
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { total, rows } = await getRoleList(this.pageParmas)
      this.fromData = rows //赋值数据
      this.pageParmas.total = total
      // 针对每一行数据添加一个编辑标记
      this.fromData.forEach(item => {
        // this.fromData.isEdit = flase // 添加一个属性，初始值为false
        // 数据响应式的问题，数据变化，视图更新
        // 添加的动态属性，不具备响应式特点
        // this.$set(对象，属性名，属性值),给对象添加一个属性，具备响应式特点
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', { name: item.name, description: item.description, state: item.state })
      })

    },
    // 切换分页时请求新的数据
    handleCurrentChange(val) {
      this.pageParmas.page = val //更新页码
      this.getRoleList()  // 更新数据
    },
    btnOk() {
      this.$refs.roleFrom.validate(async isok => {
        if (isok) {
          // 调用接口
          await addRole(this.roleFrom)
          this.getRoleList()
          this.btnCancel()
          this.$message.success('添加成功')
        }

      })
    },
    btnCancel() {
      this.$refs.roleFrom.resetFields()
      this.showDialog = false
    },
    btnEdit(row) {
      row.isEdit = true
      row.editRow = { name: row.name, description: row.description, state: row.state }
    },
    async btnEditOk(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success('更新成功')
        // 更新显示的数据
        // row.name = row.editRow.name // eslint的校验，会误判
        Object.assign(row, { ...row.editRow, isEdit: false }) // 使用，Object.assign() 合并对象,规避eslint误判


      } else {
        this.$message.warning('角色和描述不能为空')

      }
    },
    async confirmDel(id) {
      await deleteRole(id)
      this.$message.success('删除成功')
      // 判断是否是最后一页的最后一条数据
      if (this.fromData.length === 1) {
        this.pageParmas.page--
      }
      this.getRoleList()

    },
    async btnPermission(id){
      
      this.currentRoleId = id
      const {permIds} = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showPromissionDialog=true
    },
    // 点击确定时触发
    async btnRoleOk(){
      await assignPerm({
        id:this.currentRoleId,
        permIds:this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPromissionDialog=false
    }
  }

}

</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>